<template>
  <div>
    <h1>Vue Parent Component</h1>

    <!-- Vue 页面内嵌入 iframe -->
    <iframe
      ref="iframe"
      :src="iframeSrc"
      width="100%"
      height="400px"
      frameborder="0"
      @load="onIframeLoad"
    ></iframe>

    <div style="height: 400px;">
      <p>Message from iframe: {{ iframeMessage }}</p>
      <button @click="sendMessageToIframe">Send Message to Iframe</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      iframeSrc: `${process.env.BASE_URL}html/iframe.html`,
      iframeMessage: "",
    };
  },
  methods: {
    // 监听父组件与 iframe 之间的消息
    onIframeLoad() {
      window.addEventListener("message", this.receiveMessageFromIframe);
    },

    // 接收来自 iframe 的消息
    receiveMessageFromIframe(event) {
      if (event.origin !== window.location.origin) return; // 安全检查

      const data = event.data;
      if (data && data.action === "update") {
        this.iframeMessage = data.message;
      }
    },

    // 向 iframe 发送消息
    sendMessageToIframe() {
      const iframe = this.$refs.iframe;
      iframe.contentWindow.postMessage({
        action: "update",
        message: "Hello from Vue Parent!"
      }, "*");
    }
  },
  beforeDestroy() {
    // 清理事件监听器
    window.removeEventListener("message", this.receiveMessageFromIframe);
  }
};
</script>

<style scoped>
h1 {
  color: #333;
}
button {
  padding: 10px;
  background-color: #28a745;
  color: white;
  border: none;
  cursor: pointer;
}
button:hover {
  background-color: #218838;
}
</style>
